package com.iscas.green.databasechaostest.controller;

import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.*;

@RestController
@RequestMapping("/api/test")
public class DatabasetestController {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    @Qualifier("clickhouseJdbcTemplate")
    private JdbcTemplate clickhouseJdbcTemplate;

    @GetMapping("/mongodb/collections")
    public ResponseEntity<?> listCollections() {
        try {
            Set<String> collections = mongoTemplate.getCollectionNames();
            return ResponseEntity.ok(collections);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError()
                    .body("Error listing collections: " + e.getMessage());
        }
    }
    @GetMapping("/mongodb/list")
    public ResponseEntity<?> getMongoData() {
        try {
            MongoCollection<Document> collection = mongoTemplate.getCollection("1");
            List<Document> documents = collection.find().into(new ArrayList<>());

            Map<String, Object> response = new HashMap<>();
            response.put("count", documents.size());
            response.put("data", documents);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError()
                    .body("Error retrieving data: " + e.getMessage());
        }
    }
    @PostMapping("/mongodb/create")
    public ResponseEntity<?> createTestData() {
        try {
            // 创建一个测试文档
            Document testDoc = new Document()
                    .append("test", "hello world")
                    .append("timestamp", new Date());

            // 获取集合并插入文档
            MongoCollection<Document> collection = mongoTemplate.getCollection("1");
            collection.insertOne(testDoc);

            return ResponseEntity.ok(testDoc);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError()
                    .body("Error creating test data: " + e.getMessage());
        }
    }
    @GetMapping("/clickhouse")
    public Map<String, Object> getClickhouseData() {
        // 从ClickHouse的otel_logs表中获取第一条数据
        return clickhouseJdbcTemplate.queryForMap(
                "SELECT * FROM default.otel_logs LIMIT 1"
        );
    }
}